package com.example.as_sum.application;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.widget.Toast;

import com.example.as_sum.R;
import com.example.as_sum.activity.LoginActivity;
import com.example.as_sum.imageutil.FrescoUtils;
import com.example.as_sum.util.DataBaseUtil;
import com.example.as_sum.util.Log;
import com.example.as_sum.util.OkHttpUtil;
import com.example.as_sum.util.SharePerferenceUtil;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.backends.okhttp3.OkHttpImagePipelineConfigFactory;
import com.facebook.imagepipeline.core.ImagePipelineConfig;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.https.HttpsUtils;
import com.zhy.http.okhttp.log.LoggerInterceptor;

import org.apache.http.conn.ssl.SSLSocketFactory;

import java.io.InputStream;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import okhttp3.OkHttpClient;

/**
 * Created by ran on 2016/7/18.
 */
public class AppApplication extends Application {
    public static AppApplication aContext;
    private Toast singleT;
    public boolean isExit=false;
    public boolean isFirstNetwork;
    public boolean netWorkState;

    public String getToken() {
        return mToken;
    }

    public void setToken(String token) {
        mToken = token;

        Intent intent=new Intent();
        intent.setClass(getApplicationContext(),MyService.class);
        startService(intent);
    }

    private String mToken;

    // 一定要用静态的变量，即使application对象,被系统杀死也没事
    public static List<Activity> runingActivities = new ArrayList<Activity>();

    @Override
    public void onCreate() {
        super.onCreate();
        aContext=this;
        startMyCrashHandler();
        startNetService();
        DataBaseUtil.getInstance();
        OkHttpClient okHttpClient=OkHttpUtil.getInstance();
        FrescoUtils.init(getApplicationContext(),50,okHttpClient);
    }


    private void startNetService() {
        Intent intent = new Intent();
        intent.setClass(this, NetWorkService.class);
        startService(intent);
    }

    public void showMsg(String text) {
        if(singleT==null)
        {
            singleT = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG);
        }
        singleT.setText(text);
        singleT.show();
    }
    public void reStartApp(){

        final Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//这句话可以去掉
        startActivity(intent);
        System.exit(0);//这句话一定要加

    }
    private void startMyCrashHandler() {
        MyCrashHandler crashHandler = MyCrashHandler.getInstance();
        crashHandler.init(getApplicationContext());
    }

    /**
     * 判断是不是正在后台运行
     * @param context
     * @return
     */
    public boolean isRunningForeground(Context context) {
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        /**
         * am.getRunningTasks(1) 获取任务栈 1表示获取的最大数量
         */

        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        String currentPackageName = cn.getPackageName();
        // ComponentInfo{com.android.systemui/com.android.systemui.recent.RecentsActivity}
        // ComponentInfo{com.android.systemui/com.android.systemui.recent.RecentAppFxActivity}
        if (!TextUtils.isEmpty(currentPackageName)
                && currentPackageName.equals(getPackageName())) {
            return true;
        }
        return false;
    }

    /**
     * 是不是正在运行，判断当前栈顶是不是我们的App的包名
     * @param context
     * @return
     */
    public boolean isTopActivity(Activity context) {
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        /**
         * am.getRunningTasks(1) 获取任务栈 1表示获取的最大数量
         */

        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        String className = cn.getClassName();

        if (!TextUtils.isEmpty(className)
                && className.equals(context.getClass().getName())) {
            return true;
        }
        return false;
    }

    /**
     * 退出app
     * @return
     */
    public boolean isExitApp(){

        if(!isExit) {
            isExit =true;
            Toast.makeText(getApplicationContext(),"再按一次退出应用",Toast.LENGTH_SHORT).show();
            new Handler(getMainLooper()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    isExit = false;
                }
            }, 2000);
        }
        else{
            isExit=false;
        }
        return !isExit;
    }
    
    public void addActivity(Activity activity) {
        if (runingActivities != null) {
            runingActivities.add(activity);
        }
    }
    /**
     * 移除Activity
     *
     * @param activity
     */
    public void removeActivity(Activity activity) {
        if (runingActivities != null) {
            runingActivities.remove(activity);
        }
    }
    /**
     * 清除所有的activity(里面没有MainActivity的实例)
     */
    public void clearAllActivity() {
        if (runingActivities != null) {
            for (int i = 0; i < runingActivities.size(); i++) {
                Activity a = runingActivities.get(i);
                a.finish();
                runingActivities.remove(i);
                i--;
            }
        }
    }

    /**
     * @param context 关闭其他acitvity，除了自身以外
     */
    public void clearOtherActivity(Activity context) {
        if (runingActivities != null) {
            for (int i = 0; i < runingActivities.size(); i++) {
                Activity a = runingActivities.get(i);
                if (a != null && !a.equals(context)) {
                    a.finish();
                    runingActivities.remove(i);
                    i--;
                }

            }

        }
    }

    /**
     * 跳转到登陆界面
     * @param context
     * @param clearTopFlag
     */
    public void gotoLogin(Activity context, boolean clearTopFlag) {
        Intent intent = new Intent();
        if (clearTopFlag) {
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        }
        intent.setClass(context, LoginActivity.class);
        context.startActivity(intent);
    }
   public void safetyLogout(Activity context, boolean clearAll){
       if(clearAll){
           //删除本地关于用户的信息
           SharePerferenceUtil.deteleAll(context);
       }
       clearAllActivity();
       Intent intent = new Intent();
       intent.setAction(Constant.ACTION_LOGOUT);
       context.sendBroadcast(intent);
       Log.e("------>", "发送广播");
   }
    public void getAllActivity(){
        String xx="";
        for (Activity activity:runingActivities){
            String name=activity.getClass().getSimpleName();
            xx=xx+","+name;
        }
        Log.e("此时的Activity栈：", xx);
    }
}
